import requests
from xml.parsers.expat import ParserCreate

from GetZipCode import getZipCode
from ProvinceObj import ProvinceObj
from db.ProvinceDao import insertProvinces

url = 'http://www.ip138.com/post/'

provinces = []

def getProvince():
    content = requests.get(url).content.decode('gb2312')
    start = content.find('<map name=\"map_86\" id=\"map_86\">')
    end = content.find('</map>')
    content = content[start:end + len('</map>')].strip()
    print(content)

    handler = DefaultSaxHandler()
    parser = ParserCreate()
    parser.StartElementHandler = handler.start_element
    parser.EndElementHandler = handler.end_element
    parser.CharacterDataHandler = handler.char_data
    parser.Parse(content)

class DefaultSaxHandler(object):
    def start_element(self, name, attrs):
        # print('sax:start_element: %s, attrs: %s' % (name, str(attrs)))
        if name != 'map':
            name = attrs['title']
            number = attrs['href']
            object = ProvinceObj(name,number)
            provinces.append(object)

    def end_element(self, name):
        # print('sax:end_element: %s' % name)
        pass

    def char_data(self, text):
        # print('sax:char_data: %s' % text)
        pass

getProvince()
print(provinces)
# insertProvinces(provinces)
numbers = []
for obj in provinces:
    numbers.append(obj.number)
print(numbers)
getZipCode(numbers)
